<template>
	<view>
		<view class="equipmentbg">
			<navbar name="尿酸录入"></navbar>
			<view class="equipmentxy">
				<!-- <view class='container-text'>设备名称：{{name}}</view>
				<view class='container-text' style='font-size: 22rpx;'>设备ID：{{connectedDeviceId}}</view>
				<view class='container-text' style='font-size: 34rpx;'>测量结果：{{receiveText}}umol/L</view> -->
				<!-- <button @tap="startTest" :disabled="btndis">{{btnText}}</button> -->
				<view class="buzhou-one">
					<text class="bz-text">步骤1</text>请先确认设备处于工作状态，并打开手机蓝牙功能
				</view>
				<view class="buzhou-one" style="top:555upx">
					<text class="bz-text">步骤2</text>手机与设备连接成功后，采血针在手指上刺破
					手指后，试纸碰触血液，尿酸检测仪发出一声
					运行的声音。
				</view>
				<view class="buzhou-one" style="top:1140upx;">
					<text class="bz-text">步骤3</text>测量结束后请耐心等待测量结果
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import dayjs from '@/common/utils/day/day.js'
	export default {
		data() {
			return {
				chooseType: 'Bioland-BUM', //尿酸
				searching: false, //设备监听
				receiveText: '',
				name: '',
				connectedDeviceId: '',
				serviceId: '',
				notifyCharacteristicsId: '',
				writeCharacteristicsId: '',
				connected: true,
				inputText: 'Hello World!',
				name: '',
				connectedDeviceId: '',
				services: {},
				characteristics: {},
				connected: true,
				//		判断是否主动断开
				activeClose: false,
				serviceId: '',
				notifyCharacteristicsId: '',
				writeCharacteristicsId: '',
				pakInfoList: [],
				scorollTop: 100,


				clockInOrNot: false, //是否通过打卡进入
			}
		},
		onLoad(e) {
			if (e.type == 1) {
				this.clockInOrNot = true
			} else {
				this.clockInOrNot = false
			}
			this.BleInitialonlaod();
			this.Search()
			//	  屏幕保存常亮
			wx.setKeepScreenOn({
				keepScreenOn: true
			})
		},
		onReady() {

		},
		onHide() {
			this.closeBleFun();
		},
		methods: {
			// 蓝牙初始化
			BleInitialonlaod() {
				let that = this;
				console.log('onLoad');
				wx.onBluetoothAdapterStateChange(function(res) {
					console.log(res)
					that.searching = res.discovering
					if (!res.available) {
						that.searching = false
					}
				})
				wx.onBluetoothDeviceFound(function(devices) {

					let name = devices.devices[0].name
					if (name == that.chooseType) {
						console.log('获取蓝牙设备') //蓝牙设备列表
						console.log(devices.devices[0]) //蓝牙设备列表
						console.log(devices.devices[0].name) //蓝牙设备列表
						console.log(devices.devices[0])
						that.Connect(devices.devices[0])
					}
				})
			},
			// 连接设备
			Connect(data) {
				console.log(data, 7777777777777)
				var that = this
				//		chooseType: Bioland-BGM=>血糖仪       Bioland-BPM==>血压计
				let chT = this.chooseType;
				wx.stopBluetoothDevicesDiscovery({
					success: function(res) {
						console.log(res)
						that.searching = false
					}
				})
				wx.showLoading({
					title: '连接设备中...',
				})
				wx.createBLEConnection({
					deviceId: data.deviceId,
					success: function(res) {
						console.log(res)
						wx.hideLoading()
						wx.showToast({
							title: '连接成功',
							icon: 'success',
							duration: 1000
						})
						that.BleInitial({
							connectedDeviceId: data.deviceId,
							name: data.name
						})
						uni.showLoading({
							title: '测量中'
						});
					},
					fail: function(res) {
						console.log(res)
						wx.hideLoading()
						wx.showModal({
							title: '提示',
							content: '连接失败',
							showCancel: false,
							success: function(res) {
								// uni.navigateBack({
								// 	delta: 1
								// })
								that.baclkFun()
							},
						})
					}
				})
			},
			Search() {
				wx.showLoading({
					title: '搜索设备中...',
				})
				var that = this
				if (!that.searching) {
					wx.closeBluetoothAdapter({
						complete: function(res) {
							console.log(res)
							wx.openBluetoothAdapter({
								success: function(res) {
									console.log(res)
									wx.getBluetoothAdapterState({
										success: function(res) {
											console.log(res)
										}
									})
									wx.startBluetoothDevicesDiscovery({
										allowDuplicatesKey: false,
										success: function(res) {
											console.log(res)
											that.searching = true;
										}
									})
								},
								fail: function(res) {
									wx.hideLoading()
									console.log(res)
									wx.showModal({
										title: '提示',
										content: '请检查手机蓝牙是否打开',
										showCancel: false,
										success: function(res) {
											uni.navigateBack({
												delta: 1
											});
											that.searching = false
										}
									})
								}
							})
						}
					})
				} else {
					wx.stopBluetoothDevicesDiscovery({
						success: function(res) {
							console.log(res)
							that.searching = false
						}
					})
				}
			},
			pakInfoFun(Text, data) {
				let paL = this.pakInfoList
				let inf
				inf = Text + data;
				let sT = this.scorollTop + 50;
				paL.push(inf)
				this.pakInfoList = paL;
				this.scorollTop = sT;
			},
			//	断开连接
			closeBleFun() {
				let that = this;
				wx.closeBLEConnection({
					deviceId: this.connectedDeviceId,
					success: function() {
						console.log('close sucess')
						that.activeClose = true
					}
				})
			},
			//	返回
			baclkFun() {
				this.closeBleFun();
				uni.navigateBack({
					delta: 1
				})
			},
			BlelinkFail() {
				let that = this;
				setTimeout(function() {
					//			判断,如果不是主动断开连接,则提示弹框
					if (!that.activeClose) {
						wx.showModal({
							title: '提示',
							showCancel: false,
							content: '蓝牙已断开连接，请确定返回重新连接？',
							success(res) {
								if (res.confirm) {
									that.baclkFun()
								}
							}
						})
					}
				}, 500)
			},
			//	设备蓝牙匹配，发送数据包
			BleInitial(options) {
				var that = this
				that.name = options.name;
				that.connectedDeviceId = options.connectedDeviceId
				//获取蓝牙设备所有服务
				wx.getBLEDeviceServices({
					deviceId: that.connectedDeviceId,
					success: function(res) {
						let seAr = res.services
						seAr.forEach(v => {
							if (v.uuid.indexOf("00001000") > -1 || v.uuid.indexOf('0000FFB0') > -
								1) {
								that.serviceId = v.uuid
							}
						})
						//      获取蓝牙某个服务中的所有特征值
						wx.getBLEDeviceCharacteristics({
							deviceId: options.connectedDeviceId,
							serviceId: that.serviceId,
							success: function(res) {
								console.log('对应服务的特征值')
								console.log(res.characteristics)
								//              	 获取到的特征值有多个，最后要用的事能读，能写，能监听的那个值的uuid作为特征值
								let chaArr = res.characteristics
								res.characteristics.forEach(v => {
									if (v.uuid.indexOf("00001002") > -1 || v.uuid
										.indexOf('0000FFB2') > -1) {
										that.notifyCharacteristicsId = v.uuid
									}
									if (v.uuid.indexOf("00001001") > -1 || v.uuid
										.indexOf('0000FFB1') > -1) {
										that.writeCharacteristicsId = v.uuid
									}
								})
								that.pakInfoFun('设备信息serviceId：', that.serviceId)
								that.pakInfoFun('设备信息notifyCharacteristicsId：', that
									.notifyCharacteristicsId)
								that.pakInfoFun('设备信息writeCharacteristicsId：', that
									.writeCharacteristicsId)
								console.log(that.serviceId)
								console.log(that.notifyCharacteristicsId)
								console.log(that.writeCharacteristicsId)
								//启用低功耗蓝牙设备特征值变化时的 notify 功能，订阅特征值。
								//注意：必须设备的特征值支持 notify 或者 indicate 才可以成功调用。
								wx.notifyBLECharacteristicValueChange({
									state: true,
									deviceId: options.connectedDeviceId,
									serviceId: that.serviceId,
									characteristicId: that.notifyCharacteristicsId,
									success: function(res) {
										//发送'00'包,获取设备信息
										that.Send('00');
										console.log('开始发包')
									},
									fail: function(res) {
										console.log(res)
										console.log('开始发包失败')
									}
								})
							}
						})
					}
				})
				//		监听蓝牙状态:包括连接异常/断开连接
				wx.onBLEConnectionStateChange(function(res) {
					console.log(res.connected)
					that.connected = res.connected
					if (!res.connected) {
						that.BlelinkFail();
					}
				})
				//		监听低功耗蓝牙设备的特征值变化事件
				wx.onBLECharacteristicValueChange(function(res) {
					//			var that = this;
					console.log('接收数据');
					console.log(res);
					var receiveText = that.$basejs.buf2hex(res.value);
					console.log('接收到数据：' + receiveText);
					console.log(receiveText.length);
					that.pakInfoFun('接收数据：', receiveText)
					if (receiveText.length == 36) {
						//				'03':读取尿酸数据
						// that.Send('03');
					}
					if (receiveText.length == 24) {
						//处理测量结果
						receiveText = that.handleResult(receiveText);
						that.receiveText = receiveText;
						uni.hideLoading();
						that.addRecord()
					}
				})
			},
			bindInput(e) {
				this.inputText = e.detail.value
			},
			//	发包数据处理
			SendData(threeArr) {
				//		let threeArr='00';//第三位数字
				//		获取日期
				let that = this;
				let getT = new Date();
				let Ty = '',
					Tm = '',
					Td = '',
					Th = '',
					Tmi = '',
					Ts = '',
					Tdate = '',
					Tadd = '';
				Ty = getT.getFullYear() % 1000;
				Tm = getT.getMonth() + 1;
				Td = getT.getDate();
				Th = getT.getHours();
				Tmi = getT.getMinutes();
				Ts = getT.getSeconds();
				Tdate = Ty + '-' + Tm + '-' + Td + ' ' + Th + ':' + Tmi + ':' + Ts;
				//		获取包的最后一位数字
				Tadd = 90 + 10 + Number(threeArr) + Ty + Tm + Td + Th + Tmi + Ts + 2;
				if (Tadd > 255) {
					//			获取最后两位
					Tadd = (Tadd % 255);
				}
				//		转十六进制
				threeArr = '0x' + threeArr.toString(16);
				Ty = '0x' + Ty.toString(16);
				Tm = '0x' + Tm.toString(16);
				Td = '0x' + Td.toString(16);
				Th = '0x' + Th.toString(16);
				Tmi = '0x' + Tmi.toString(16);
				Ts = '0x' + Ts.toString(16);
				Tadd = '0x' + Tadd.toString(16);
				let sendArr = ['0x5A', '0x0A', threeArr, Ty, Tm, Td, Th, Tmi, Ts, Tadd];

				let val = new Uint8Array(sendArr);
				var receiveText = that.$basejs.buf2hex(val.buffer)
				console.log(threeArr + '--数据：' + receiveText)
				if (threeArr == '0x00') {
					this.pakInfoFun('发送信息读取包00：', receiveText)
				} else if (threeArr == '0x03') {
					this.pakInfoFun('发送数据读取包03：', receiveText)
				}
				return sendArr;
			},
			//	发包
			Send(threeArr) {
				var that = this;
				if (that.connected) {
					//发包内容
					let val = new Uint8Array(that.SendData(threeArr));
					wx.writeBLECharacteristicValue({
						deviceId: that.connectedDeviceId,
						serviceId: that.serviceId,
						characteristicId: that.writeCharacteristicsId,
						value: val.buffer,
						success: function(res) {
							console.log('发包成功')
							console.log(res)
							that.pakInfoFun('发包成功：', threeArr)
						},
						fail: function(res) {
							console.log(res)
							console.log('发包失败')
							that.pakInfoFun('发包失败：', threeArr)
						},
						complete: function(res) {
							console.log('完成')
							console.log(res)

						}

					})
				} else {
					that.BlelinkFail();
				}
			},
			// 记录尿酸
			addRecord() {
				let time = new Date(+new Date() + 8 * 3600 * 1000).toJSON().substr(0, 19).replace("T", " ")
				let _this = this,
					fdata = {
						deviceType: 'URIC_ACID',
						recordTime: dayjs(time).format('YYYY-MM-DD'),
						createTime: time,
						inputType: 2, //1手动 2设备
						userId: uni.getStorageSync(global.IS_DEV?'USER_DATA_BSY_T':'USER_DATA_BSY_Z').userId,
						mac: this.name, //设备mac
						deviceId: this.connectedDeviceId, //设备id
						healthDataId: '',
						healthData: JSON.stringify({
							value: this.receiveText
						}),
					};
				this.$api.post(global.apiUrls.addRecord, fdata).then(res => {
					if (res.data.code == 1000) {
						_this.value1 = ''
						uni.showToast({
							title: res.data.message,
							duration: 2000
						});
						if (this.clockInOrNot) {
							let pages = getCurrentPages(); //当前页面栈
							let beforePage = pages[pages.length - 2]; //指定调用页面为上个页面
							beforePage.$vm.punchTheClock() //getData 是你要调用上个页面的方法，微信小程序不需要用 $vm
							uni.navigateBack({
								delta: 1
							});
						}
						setTimeout(() => {
							// uni.navigateBack({
							// 	delta: 1
							// });
							_this.baclkFun()
						}, 2000);
					} else {
						uni.showToast({
							title: res.data.message,
							icon: "none",
							duration: 2000
						});
					}
				}).catch(err => {})
			},
			//处理得出的结果
			handleResult(data) {
				var testValue1 = data.substr(18, 2),
					testValue2 = data.substr(20, 2);
				console.log('testValue1', testValue1);
				console.log('testValue2', testValue2);
				var testValue3 = this.hex2int(testValue2 + testValue1) //收缩压
				console.log('testValue3', testValue3);
				// var testValue3='0x'+testValue2+testValue1;
				//保留1位小数
				// testValue3=parseInt(parseInt(testValue3)/10)/10;
				return testValue3
			},
			// 16进制转10
			hex2int(hex) {
				var len = hex.length,
					a = new Array(len),
					code;
				for (var i = 0; i < len; i++) {
					code = hex.charCodeAt(i);
					if (48 <= code && code < 58) {
						code -= 48;
					} else {
						code = (code & 0xdf) - 65 + 10;
					}
					a[i] = code;
				}
				return a.reduce(function(acc, c) {
					acc = 16 * acc + c;
					return acc;
				}, 0);
			},
		}
	}
</script>

<style lang="scss">
	.equipmentbg {
		width: 100vw;
		min-height: 100vh;
		background: url(http://static.bsyjk.cn/equipmentbg/0DB19D05B0D1471BBCBDD70DAEDE2374.png)no-repeat;
		background-size: 100% 100%;

		.equipmentxy {
			width: 750upx;
			height: 1460upx;
			background: url(http://static.bsyjk.cn/uricAcidBg/AF261FCB32F243C49DA314B5F931DA12.png)no-repeat;
			background-size: 100% 100%;
			position: relative;
			color: #2EA7E0;
			text-align: center;

			.buzhou-one {
				width: 690upx;
				left: 50%;
				transform: translateX(-50%);
				font-size: 26upx;
				position: absolute;
				top: 74upx;

				.bz-text {
					font-size: 36upx;
					padding-right: 20upx;
				}
			}
		}
	}

	page {
		width: 100%;
		height: 100%;
		font-size: 30rpx;
	}

	.pressure {
		width: 100%;
		padding: 20rpx;
		box-sizing: border-box;
		border-top: 1rpx solid #CCCCCC;
		height: auto;
	}

	.pressure .pres-text {
		width: 100%;
		padding: 10rpx;
		font-size: 30rpx;
	}

	.pressure-btn {
		width: 100%;
		padding: 20rpx;
		box-sizing: border-box;
		height: auto;
	}

	.pressure-btn button {
		float: left;
		width: 46%;
		margin: 0 1%;
	}

	.pressure-info {
		width: 100%;
		position: absolute;
		top: 440rpx;
		left: 0;
		bottom: 10rpx;
		overflow: auto;
	}

	.pressure-info .info-list {
		width: 100%;
		height: auto;
		padding: 15rpx 10rpx;
		box-sizing: border-box;
	}
</style>
